<?php

declare(strict_types=1);

namespace app\middleware;

use app\common\result\Result;
use app\model\Admin;
use app\model\Role;
use thans\jwt\facade\JWTAuth;

class CheckPermission
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $token = JWTAuth::getToken();
        $payload = JWTAuth::auth();
        $uid = $payload['uid'];
        $request->uid = $uid;

        if ($uid == '22') {
            return $next($request);
        }

        // 判断权限
        $url = $request->baseUrl();

        // 查询管理员权限
        $admin = Admin::with('roles')->find($uid);
        $role = Role::with('permissions')->find($admin->roles->id);

        $permissions = $role->permissions;
        $enough = false;

        foreach ($permissions as $key => $value) {
            // echo $key . ":" . $value;
            if ($value->path == $url) {
                $enough = true;
            }
        }


        if ($enough) {
            return $next($request);
        } else {
            return Result::Error(401, '请联系管理员授权');
        }
    }
}
